<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getApiUrl, API_ENDPOINTS } from '../config/api'

interface MaintenanceRecord {
  id: number
  facility: string
  location: string
  type: string
  status: string
  priority: string
  reportDate: string
  nextMaintenance: string
}

interface FacilityStatus {
  id: number
  name: string
  status: string
  lastCheck: string
}

const records = ref<MaintenanceRecord[]>([])
const facilityStatus = ref<FacilityStatus[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const formData = ref({
  facility: '',
  location: '',
  type: '',
  status: '计划中',
  priority: '普通',
  reportDate: '',
  nextMaintenance: ''
})

// Fetch maintenance records from API
const fetchRecords = async () => {
  try {
    loading.value = true
    const response = await fetch(getApiUrl(API_ENDPOINTS.facility))
    if (!response.ok) throw new Error('获取数据失败')
    const data = await response.json()
    // 格式化日期显示
    records.value = Array.isArray(data) ? data.map(record => ({
      ...record,
      reportDate: record.reportDate?.split('T')[0] || '',
      nextMaintenance: record.nextMaintenance?.split('T')[0] || ''
    })) : []
    // 更新设施状态
    updateFacilityStatus()
  } catch (error) {
    console.error('获取维护记录失败:', error)
    ElMessage.error('获取维护记录失败')
    records.value = []
  } finally {
    loading.value = false
  }
}

// Add new maintenance record
const addRecord = async () => {
  try {
    // 检查日期是否存在
    if (!formData.value.reportDate || !formData.value.nextMaintenance) {
      ElMessage.error('请选择日期')
      return
    }

    // 格式化日期
    const formattedData = {
      ...formData.value,
      reportDate: formData.value.reportDate instanceof Date 
        ? formData.value.reportDate.toISOString().split('T')[0]
        : formData.value.reportDate.split('T')[0],
      nextMaintenance: formData.value.nextMaintenance instanceof Date
        ? formData.value.nextMaintenance.toISOString().split('T')[0]
        : formData.value.nextMaintenance.split('T')[0]
    }

    console.log('提交数据:', formattedData)

    const response = await fetch(getApiUrl(API_ENDPOINTS.facility), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formattedData)
    })

    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '添加失败')
    }
    
    ElMessage.success('添加维护记录成功')
    dialogVisible.value = false
    await fetchRecords() // 获取最新记录
    updateFacilityStatus() // 立即更新设施状态
    resetForm()
  } catch (error) {
    console.error('添加维护记录失败:', error)
    ElMessage.error(error.message || '添加维护记录失败')
  }
}

// Update maintenance record
const updateRecord = async (id, newStatus) => {
  try {
    console.log('Updating record:', { id, newStatus })

    // 获取当前记录
    const currentRecord = records.value.find(r => r.id === id)
    if (!currentRecord) {
      throw new Error('找不到要更新的记录')
    }

    // 构建更新数据
    const updateData = {
      status: newStatus
    }

    console.log('Update data:', updateData)

    const response = await fetch(getApiUrl(`${API_ENDPOINTS.facility}/${id}`), {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(updateData)
    })

    const responseData = await response.json()
    if (!response.ok) {
      throw new Error(responseData.message || '更新失败')
    }
    
    ElMessage.success('更新维护记录成功')
    await fetchRecords() // 这里会自动更新设施状态
  } catch (error) {
    console.error('更新维护记录失败:', error)
    ElMessage.error(error.message || '更新维护记录失败')
  }
}

// Handle status update
const handleStatusUpdate = async (row, newStatus) => {
  try {
    await ElMessageBox.confirm(
      `确定将维护记录"${row.facility}"的状态更新为"${newStatus}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await updateRecord(row.id, newStatus)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态更新失败:', error)
      ElMessage.error('状态更新失败')
    }
  }
}

const resetForm = () => {
  formData.value = {
    facility: '',
    location: '',
    type: '',
    status: '计划中',
    priority: '普通',
    reportDate: '',
    nextMaintenance: ''
  }
}

// Initialize facility status data
const initializeFacilityStatus = () => {
  facilityStatus.value = [
    { id: 1, name: '电梯', status: '正常', lastCheck: '2024-03-10' },
    { id: 2, name: '空调系统', status: '正常', lastCheck: '2024-03-15' },
    { id: 3, name: '热水系统', status: '正常', lastCheck: '2024-03-12' },
    { id: 4, name: '监控系统', status: '正常', lastCheck: '2024-03-14' },
    { id: 5, name: '消防系统', status: '正常', lastCheck: '2024-03-10' },
    { id: 6, name: '照明系统', status: '正常', lastCheck: '2024-03-08' },
    { id: 7, name: '门禁系统', status: '正常', lastCheck: '2024-03-15' },
    { id: 8, name: '供暖系统', status: '正常', lastCheck: '2024-03-13' },
    { id: 9, name: '洗衣设备', status: '正常', lastCheck: '2024-03-11' },
    { id: 10, name: '厨房设备', status: '正常', lastCheck: '2024-03-14' }
  ]
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '正常':
      return 'success';
    case '维修中':
      return 'warning';
    case '待维修(紧急)':
      return 'danger';
    case '待维修(高)':
      return 'warning';
    case '待维修':
      return 'info';
    default:
      return 'info';
  }
};

// 获取表格状态标签类型
const getTableStatusType = (status, priority = '普通') => {
  if (status === '已完成') return 'success';
  if (status === '处理中') return 'warning';
  if (status === '计划中') {
    if (priority === '紧急') return 'danger';
    if (priority === '高') return 'warning';
    return 'info';
  }
  return 'info';
};

// 更新设施状态
const updateFacilityStatus = () => {
  // 首先重置所有设施状态为正常
  facilityStatus.value.forEach(facility => {
    facility.status = '正常';
  });

  // 按照时间排序维护记录，确保使用最新的状态
  const sortedRecords = [...records.value].sort((a, b) => 
    new Date(b.reportDate).getTime() - new Date(a.reportDate).getTime()
  );

  // 遍历维护记录，更新设施状态
  sortedRecords.forEach(record => {
    const facilityIndex = facilityStatus.value.findIndex(f => f.name === record.facility);
    if (facilityIndex !== -1) {
      // 根据维护记录状态和优先级更新设施状态
      if (record.status === '处理中') {
        facilityStatus.value[facilityIndex].status = '维修中';
      } else if (record.status === '计划中') {
        // 如果是计划中，根据优先级设置不同状态
        if (record.priority === '紧急') {
          facilityStatus.value[facilityIndex].status = '待维修(紧急)';
        } else if (record.priority === '高') {
          facilityStatus.value[facilityIndex].status = '待维修(高)';
        } else {
          facilityStatus.value[facilityIndex].status = '待维修';
        }
      }
      // 更新最后检查时间
      facilityStatus.value[facilityIndex].lastCheck = record.reportDate;
    }
  });
};

onMounted(async () => {
  initializeFacilityStatus()
  await fetchRecords() // 初始化时会自动更新设施状态
})
</script>

<template>
  <div class="facility">
    <div class="header">
      <h2>设施维护</h2>
      <el-button type="primary" @click="dialogVisible = true">报修登记</el-button>
    </div>

    <el-row :gutter="24" class="status-cards">
      <el-col :span="6" v-for="item in facilityStatus" :key="item.id">
        <el-card shadow="hover" :class="{ 'maintenance-card': item.status === '维修中' }">
          <div class="status-card-content">
            <div class="status-info">
              <h3>{{ item.name }}</h3>
              <el-tag :type="getStatusType(item.status)">
                {{ item.status }}
              </el-tag>
            </div>
            <div class="last-check">
              上次检查: {{ item.lastCheck }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="maintenance-records">
      <h3>维护记录</h3>
      <el-table 
        :data="records" 
        style="width: 100%; margin-top: 20px;"
        v-loading="loading"
      >
        <el-table-column prop="facility" label="设施名称" />
        <el-table-column prop="location" label="位置" />
        <el-table-column prop="type" label="维护类型" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getTableStatusType(row.status, row.priority)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级">
          <template #default="{ row }">
            <el-tag :type="row.priority === '紧急' ? 'danger' : row.priority === '高' ? 'warning' : 'info'">
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reportDate" label="报修日期" />
        <el-table-column prop="nextMaintenance" label="下次维护" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              @click="handleStatusUpdate(row, '已完成')"
              :disabled="row.status === '已完成'"
            >
              完成
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleStatusUpdate(row, '处理中')"
              :disabled="row.status === '处理中'"
            >
              更新
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Add Maintenance Record Dialog -->
    <el-dialog
      v-model="dialogVisible"
      title="报修登记"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="设施名称" required>
          <el-select v-model="formData.facility" style="width: 100%">
            <el-option 
              v-for="item in facilityStatus"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="位置" required>
          <el-select v-model="formData.location" style="width: 100%">
            <el-option label="A栋" value="A栋" />
            <el-option label="B栋" value="B栋" />
            <el-option label="全院" value="全院" />
          </el-select>
        </el-form-item>
        <el-form-item label="维护类型" required>
          <el-select v-model="formData.type" style="width: 100%">
            <el-option label="定期保养" value="定期保养" />
            <el-option label="维修" value="维修" />
            <el-option label="检修" value="检修" />
            <el-option label="更换" value="更换" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" required>
          <el-select v-model="formData.priority" style="width: 100%">
            <el-option label="普通" value="普通" />
            <el-option label="高" value="高" />
            <el-option label="紧急" value="紧急" />
          </el-select>
        </el-form-item>
        <el-form-item label="报修日期" required>
          <el-date-picker
            v-model="formData.reportDate"
            type="date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            :clearable="false"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="下次维护" required>
          <el-date-picker
            v-model="formData.nextMaintenance"
            type="date"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            :clearable="false"
            :editable="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRecord">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.facility {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.status-cards {
  margin-bottom: 30px;
}

.status-card-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.last-check {
  font-size: 14px;
  color: #909399;
}

.maintenance-records {
  margin-top: 30px;
}

.maintenance-records h3 {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.maintenance-card {
  border: 1px solid #e6a23c;
  background-color: #fdf6ec;
}

:deep(.el-card__body) {
  padding: 16px;
}
</style>